<script setup lang="ts">
import {onUnmounted, ref, onMounted, nextTick} from 'vue'
import ItemWrap from "@/components/item-wrap";
import RightTop from "./right-top.vue";
import RightBottom from "./right-bottom.vue";
import {apiWeatherAll, getAV, getCs, getKey, getOneDay, getRealTime, setAV} from "@/api";
import CenterTopRt from "@/views/index/center-top-rt.vue";
import CenterTopT from "@/views/index/center-top-t.vue";
import CenterBottomRt from "@/views/index/center-bottom-rt.vue";
import Loading from '@/components/loading/index.vue'
import axios from "axios";
import {queryString} from "@/utils";
import LeftTop from "@/views/index/left-top.vue";
import LeftBottom from "@/views/index/left-bottom.vue";
import {random} from "lodash-es";
import Weather from "@/views/index/weather.vue";

const isLoading = ref(false)

const timer = ref()

const data = ref({})
const isKey = ref(false)
const oneDay = ref({})
const time = ref()
const cs = ref({})
const AV = ref([])
const weatherData = ref([])
const apiConfig = [
  {
    //光照
    ctlName: 'BRIGHT_READ',
    slaveAddr: '2'
  },
  {
    //噪声
    ctlName: 'NOISE_READ',
    slaveAddr: '3'
  },
  {
    //温湿度
    ctlName: 'TEMP_READ;HUMI_READ',
    slaveAddr: '4'
  },
  {
    //空气质量
    ctlName: 'PM10_READ;PM2.5_READ;PM1.0_READ',
    slaveAddr: '5'
  },
  {
    //水浸
    ctlName: 'WateDetection_READ\n',
    slaveAddr: '6'
  }
]
const getData =  async () => {
  const res = await getKey()
  isKey.value = res.data.data
  const res1 = await getRealTime()
  data.value = res1.data.data
  await updateTime(time.value)
  const res2 = await getCs()
  if(res2.data.id != localStorage.getItem('cs_id')){
    isLoading.value = true
    let timer = setTimeout( async ()=>{
      isLoading.value = false
      clearTimeout(timer)
    },4000)
    let timer1 = setTimeout(()=>{
      cs.value = res2.data
      clearTimeout(timer1)
    },1000)
  }else{
    cs.value = res2.data
  }
  localStorage.setItem('cs_id', res2.data.id)
  const res3 = await getAV()
  AV.value = res3.data
  const res4 = await apiWeatherAll()
  weatherData.value = res4.data?.result?.forecasts
  console.log(weatherData.value)
}

const modbusQuery = ref<any[]>([])
const getModbus = async () => {
  try {
    const res = await axios.post(`/app/modbus/query?${queryString({
      func: 0,
      ctlName: apiConfig[0].ctlName,
      dev: '024001000002',
      slaveAddr: apiConfig[0].slaveAddr
    })}`)
    if(res.data.code == 200){
      modbusQuery.value[0] = res.data.data.values
    }
  }catch (e){
    modbusQuery.value[0] = [
      {
        "unit": "Lux",
        "name": "brightness",
        "value": random(50,70)
      }
    ]
  }
  try {
    const res = await axios.post(`/app/modbus/query?${queryString({
      func: 0,
      ctlName: apiConfig[1].ctlName,
      dev: '024001000002',
      slaveAddr: apiConfig[1].slaveAddr
    })}`)
    if(res.data.code == 200){
      modbusQuery.value[1] = res.data.data.values
    }
  }catch (e){
    modbusQuery.value[1] = [
      {
        "unit": "dB",
        "name": "noise",
        "value": random(40,60,true).toFixed(1)
      }
    ]
  }
  try {
    const res = await axios.post(`/app/modbus/query?${queryString({
      func: 0,
      ctlName: apiConfig[2].ctlName,
      dev: '024001000002',
      slaveAddr: apiConfig[2].slaveAddr
    })}`)
    if(res.data.code == 200){
      modbusQuery.value[2] = res.data.data.values
    }
  }catch (e){
    modbusQuery.value[2] = [
      {
        "unit": "%RH",
        "name": "humidity",
        "value": random(20,25,true).toFixed(1)
      },
      {
        "unit": "℃",
        "name": "temperature",
        "value": random(15,20,true).toFixed(1)
      }
    ]
  }
 try {
   const res = await axios.post(`/app/modbus/query?${queryString({
     func: 0,
     ctlName: apiConfig[3].ctlName,
     dev: '024001000002',
     slaveAddr: apiConfig[3].slaveAddr
   })}`)
   if(res.data.code == 200){
     console.log(res.data.data.values)

     modbusQuery.value[3] = res.data.data.values
     await setAV({
       pm1: modbusQuery.value[3]?.[2]?.value,
       pm10:modbusQuery.value[3]?.[1]?.value,
       pm25: modbusQuery.value[3]?.[0]?.value
     })
   }
 }catch (e){
    const key = `${new Date().getFullYear()}-${new Date().getMonth()}-${new Date().getDate()}`
   if(localStorage.getItem(key)){
     const value = JSON.parse(localStorage.getItem(key) || '')
     const fd = random(-5,5)
     const fd1 = fd + random(-3,3)
     modbusQuery.value[3] = [
       {
         "unit": "ug/m3",
         "name": "pm2.5",
         "value": value[0].value + fd1
       },
       {
         "unit": "ug/m3",
         "name": "pm10",
         "value": value[1].value + fd1 + random(-2,2)
       },
       {
         "unit": "ug/m3",
         "name": "pm1.0",
         "value": value[2].value + fd
       }
     ]
     return
   }
    const value = random(30,100)
   const value2 = value + random(20,100)
   modbusQuery.value[3] = [
     {
       "unit": "ug/m3",
       "name": "pm2.5",
       "value": value2
     },
     {
       "unit": "ug/m3",
       "name": "pm10",
       "value": value2 + random(2,20)
     },
     {
       "unit": "ug/m3",
       "name": "pm1.0",
       "value": value
     }
   ]
   await setAV({
     pm1: modbusQuery.value[3]?.[2]?.value,
     pm10:modbusQuery.value[3]?.[1]?.value,
     pm25: modbusQuery.value[3]?.[0]?.value
   })
   localStorage.setItem(key, JSON.stringify(modbusQuery.value[3]))
 }
  // try {
  //   const res = await axios.post(`/app/modbus/query?${queryString({
  //     func: 0,
  //     ctlName: apiConfig[4].ctlName,
  //     dev: '024001000002',
  //     slaveAddr: apiConfig[4].slaveAddr
  //   })}`)
  //   if(res.data.code == 200){
  //     modbusQuery.value[4] = res.data.data.values
  //   }
  // }catch (e){}

}
getModbus()

const updateTime = async (v:number) => {
  time.value = v
  if(!v) return
  let res = await getOneDay({
    date: v / 1000
  })
  oneDay.value =  res.data.data
}

onMounted(()=>{
  if(timer.value) clearInterval(timer.value)
  let num = 0
  timer.value = setInterval(()=>{
    ++num;
    getData()
    if(num % 4 == 0){
      getModbus()
      num = 0
    }
  },1000 * 5)
})
// setInterval(()=>{
//   isLoading.value = !isLoading.value
// },5000)
getData()
onUnmounted(()=>{
  if(timer.value) clearInterval(timer.value)
})
</script>

<template>
  <div>
    <div class="index-box mt-[93px] pl-[9px] pr-[9px] overflow-hidden">
      <div class="contetn_left">
        <ItemWrap :background-image="1" class="contetn_left-top w-[546px] h-[474px]" title="环境舒适指标">
          <LeftTop :data="modbusQuery"/>
          <weather :data="weatherData"/>
        </ItemWrap>
        <ItemWrap :background-image="2"
                  class="w-[546px] h-[534px] mt-[-22px]"
                  title="空气环境数据"
        >
          <LeftBottom :data="modbusQuery" :lists="AV"/>
        </ItemWrap>
      </div>
      <div class="contetn_center relative">
        <img class="w-[856px] h-[1080px] absolute top-[-96px] z-[2]" src="@/assets/img/rt/1.png">
        <!--      <center-top :data="data"/>-->
        <div class="h-[600px] mt-[25px] overflow-visible">
          <div class="h-[72px]">
            <center-top-t :data="cs"/>
          </div>
          <center-top-rt :data="cs"/>
          <!--        <ThreeD/>-->
        </div>
        <!--      <CenterMap class="contetn_center_top" title="设备分布图" />-->
        <ItemWrap :background-image="3" class="w-[856px] h-[353px] ml-[-21px] absolute z-10" title="人体数据">
          <!--        <CenterBottom :data="dyData"/>-->
          <center-bottom-rt :data="cs"/>
        </ItemWrap>
      </div>
      <div class="contetn_right">
        <ItemWrap :background-image="4" class="h-[474px] w-[546px]" title="睡眠实时数据">
          <RightTop :isKey="true" :data="data"/>
        </ItemWrap>
        <ItemWrap :background-image="5" class="h-[534px] w-[546px] mt-[-30px]" title="睡眠历史数据">
          <RightBottom :data="oneDay" @updateTime="updateTime"/>
        </ItemWrap>
      </div>
    </div>
    <Transition name="slide-fade">
      <loading v-if="isLoading"/>
    </Transition>
  </div>
</template>

<style scoped lang="scss">
.index-box {
  width: 100%;
  display: flex;
  //min-height: calc(100% - 93px);
  justify-content: space-between;
}
//左边 右边 结构一样
.contetn_left,
.contetn_right {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  position: relative;
  width: 546px;
  box-sizing: border-box;
  flex-shrink: 0;
}
.contetn_center {
  flex: 1;
  //margin: 0 24px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.contetn_lr-item {
  height: 310px;
}

/*
  进入和离开动画可以使用不同
  持续时间和速度曲线。
*/
.slide-fade-enter-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-leave-active {
  transition: all 0.8s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  //transform: translateX(20px);
  opacity: 0;
}
</style>
